package com.yc.weixin.web.Handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yc.utils.YcUtils;
import com.yc.weixin.service.CoreService;
import com.yc.weixin.service.impl.CoreServiceImpl;
import com.yc.weixin.util.SignUtil;

public class CoreServlet extends HttpServlet {
	
	CoreService coreService=new CoreServiceImpl();
	
	private static final long serialVersionUID = -6386847696210638028L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//微信加密签名
		String signature=request.getParameter("signature");
		//时间搓
		String timestamp=request.getParameter("timestamp");
		//随机数
		String nonce=request.getParameter("nonce");
		//随机字符串
		String echostr=request.getParameter("echostr");
		PrintWriter out=response.getWriter();
		try {	
			if(   SignUtil.checkSignature(signature, timestamp, nonce)){	
				out.println(  echostr);
			}
		} catch (NoSuchAlgorithmException e) {
			YcUtils.logger.error(e.getMessage());
			out.println(   e.getMessage() );
		}
		out.close();
		out=null;		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		//微信加密签名
		String signature=request.getParameter("signature");
		//时间搓
		String timestamp=request.getParameter("timestamp");
		//随机数
		String nonce=request.getParameter("nonce");
		//随机字符串
		String echostr=request.getParameter("echostr");
		PrintWriter out=response.getWriter();
		try {
			YcUtils.logger.debug(    signature+"  "+timestamp+"  "+nonce);
			YcUtils.logger.debug(    SignUtil.checkSignature(signature, timestamp, nonce));
			if(   SignUtil.checkSignature(signature, timestamp, nonce)){
				String respXml=coreService.processRequest(request);
				YcUtils.logger.debug(    respXml);
				out.println(  respXml);
			}
		} catch (NoSuchAlgorithmException e) {
			YcUtils.logger.error(e.getMessage());
			out.println(   e.getMessage() );
		}
		out.close();
		out=null;		
	}

}
